<template>
  <div class="introduce">
    <div class="title">团购介绍</div>

    <div class="ipt-title">
      <nut-input v-model="formData.title" max-length="100" placeholder="请输入团购标题" />
    </div>

    <div class="ipt-content">
      <div class="content">
        <template
          v-if="formData.content.length > 0"
          v-for="(item, index) in formData.content"
          :key="item.id"
        >
          <introduce-item
            ref="introItemRef"
            :product-detail="item"
            :is-dis-move-up="isDisMoveTool('up', item.id)"
            :is-dis-move-down="isDisMoveTool('down', item.id)"
            @del-intro="handleDelIntro"
            @move-intro="handleMove"
          ></introduce-item>
        </template>
        <template v-else>
          <div class="content-default" @click="handleItemClick(3)">请输入团购内容</div>
        </template>
      </div>

      <ul class="bottom-box">
        <li class="box-item" @click="handleItemClick(1)">
          <nut-uploader ref="uploadRef" url="#" :before-upload="beforeUpload" accept="image/*">
            <img src="@/assets/addstart/introduce/introduce_first.png" alt="" />
            <span>大图</span>
          </nut-uploader>
        </li>

        <li class="box-item" @click="handleItemClick(2)">
          <nut-uploader ref="uploadRef" url="#" :before-upload="beforeUpload" accept="image/*">
            <img src="@/assets/addstart/introduce/introduce_second.png" alt="" />
            <span>小图</span>
          </nut-uploader>
        </li>

        <li class="box-item" @click="handleItemClick(3)">
          <img src="@/assets/addstart/introduce/introduce_fourth.png" alt="" />
          <span>文字</span>
        </li>

        <!-- <li class="box-item" @click="handleItemClick(4)">
          <nut-uploader ref="uploadRef" url="#" :before-upload="beforeUpload" accept="video/*">
            <img src="@/assets/addstart/introduce/introduce_third.png" alt="" />
            <span>视频</span>
          </nut-uploader>
        </li> -->
      </ul>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import IntroduceItem from './introduce-item.vue'
  import { nanoid } from 'nanoid'
  import { reactive, ref } from 'vue'
  import { uploadImgApi, getOSTokenApi } from '@/api/addstart'
  import { getClient, ossPath } from '@/utils/alioss'

  // ------ data
  const uploadRef = ref<any>(null)
  const introItemRef = ref<InstanceType<typeof IntroduceItem>>()
  const currentWhich = ref(1)
  const formData = reactive({
    title: '',
    content: [] as any[]
  })
  const credentials = ref<any>({
    securityToken: '',
    accessKeySecret: '',
    accessKeyId: ''
  })

  // ------ methods
  const handleItemClick = (which: number) => {
    const payload = {
      id: nanoid(),
      text: '',
      bigImage: '',
      smallImage: '',
      type: which
    }
    currentWhich.value = which

    if (which == 3) {
      formData.content.push(payload)
    }
  }
  const isDisMoveTool = (type: string, id: any) => {
    const index = formData.content.findIndex((item) => item.id == id)

    if (type == 'up') {
      return index == 0 ? true : false
    } else {
      return index == formData.content.length - 1 ? true : false
    }
  }
  const handleMove = ({ type, id }: any) => {
    const index = formData.content.findIndex((item) => item.id == id)
    const item = formData.content.find((item) => item.id == id) as any
    formData.content.splice(index, 1)

    if (type == 'up') {
      formData.content.splice(index - 1, 0, item)
    } else {
      formData.content.splice(index + 1, 0, item)
    }
  }
  const handleDelIntro = (id: any) => {
    formData.content = [...formData.content.filter((item) => item.id != id)]
  }
  const beforeUpload = (fileList: File[]) => {
    // uploadImg(fileList[0]);
    uploadOSS(fileList[0], 'image')

    return new Promise((resolve) => {
      resolve(fileList)
    })
  }

  // ------ request
  // 接口：上传图片
  async function uploadImg(imgfile: File) {
    const res = await uploadImgApi({ imgfile })
    if (res.code == 0) {
      const { img_key } = res.result
      const payload = {
        id: nanoid(),
        text: '',
        bigImage: currentWhich.value == 1 ? img_key : '',
        smallImage: currentWhich.value == 2 ? img_key : '',
        type: currentWhich.value
      }
      formData.content.push(payload)
    }
  }
  // 接口：获取OSS Token
  async function getOSSToken() {
    const res = await getOSTokenApi()
    if (res.code == 0) {
      const { accessKeyId, accessKeySecret, securityToken } = res.result.credentials
      credentials.value.accessKeyId = accessKeyId
      credentials.value.accessKeySecret = accessKeySecret
      credentials.value.securityToken = securityToken
    }
  }
  async function uploadOSS(file: any, fileType: any) {
    var imgUrl = ossPath(file, fileType)
    getClient(
      credentials.value.accessKeyId,
      credentials.value.accessKeySecret,
      credentials.value.securityToken
    )
      .multipartUpload(imgUrl, file)
      .then((res: any) => {
        if (res.res.statusCode == 200) {
          var pathurl = res.name.replace('image/', '')

          const payload = {
            id: nanoid(),
            text: '',
            bigImage: currentWhich.value == 1 ? pathurl : '',
            smallImage: currentWhich.value == 2 ? pathurl : '',
            type: currentWhich.value
          }
          formData.content.push(payload)
        }
      })
  }

  // ------ lifecycle
  // function setupInit() {
  //   const localEditItemData = window.localStorage.getItem('editItemData')
  //   if (localEditItemData) {
  //     const editItemData = JSON.parse(localEditItemData)
  //     formData.title = editItemData.title
  //     editItemData.image_text_vos &&
  //       editItemData.image_text_vos.forEach((item: any) => {
  //         let smallImage: any[] = []
  //         item.content_list && item.content_list.forEach((it: any) => smallImage.push(it))

  //         formData.content.push({
  //           id: nanoid(),
  //           text: item.content ?? '',
  //           bigImage: item.content ?? '',
  //           smallImage,
  //           type: item.type
  //         })
  //       })
  //   }
  // }
  // setupInit()

  // ------ expose
  const resetData = () => {
    formData.title = ''
    formData.content = []
  }
  const handleCommit = () => {
    if (introItemRef.value instanceof Array) {
      const arr: any[] = []
      for (const item of introItemRef.value) {
        const res = item?.submit()
        arr.push(res)
      }

      return { title: formData.title, content: arr }
    }
  }
  // ------ lifecycle
  function setupInit() {
    getOSSToken()
  }
  setupInit()

  defineExpose({ handleCommit, resetData })
</script>

<style lang="scss" scoped>
  .introduce {
    position: relative;
    width: 710px;
    background: #ffffff;
    border-radius: 20px;
    margin-top: -136px;
    z-index: 2;

    .title {
      display: flex;
      align-items: center;
      height: 90px;
      padding: 0 20px;
      font-size: 32px;
      font-family: PingFang-SC-Medium, PingFang-SC;
      font-weight: 500;
      color: #000000;
    }

    .ipt-title {
      height: 89px;
      padding: 0 20px;
      border-top: 1px solid #eeeeee;
      border-bottom: 1px solid #eeeeee;

      :deep(.nut-input) {
        width: 100%;
        height: 100%;
        border: none;
        padding-left: 0;
        padding-right: 0;

        .input-text {
          width: 100%;
        }
      }
    }

    .ipt-content {
      min-height: 339px;
      padding: 0 20px;

      .content {
        min-height: 194px;

        .content-default {
          font-size: 30px;
          font-weight: 400;
          color: #666666;
          margin-top: 29px;
        }
      }

      :deep(.nut-textarea) {
        height: 194px;
        border: none;
        padding-left: 0;
        padding-right: 0;
        padding-bottom: 0;
      }

      .bottom-box {
        display: flex;
        padding: 25px 0 35px 0;

        .box-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 142px;
          transform: translateX(-20px);

          img {
            display: block;
            width: 48px;
          }

          span {
            font-size: 24px;
            font-family: PingFang-SC-Regular, PingFang-SC;
            font-weight: 400;
            color: #666666;
            margin-top: 7px;
          }
        }
      }
    }

    :deep(.nut-uploader__slot) {
      width: 100%;
      border: 1px soild red;
      display: flex;
      flex-direction: column;
    }
    :deep(.nut-uploader__preview) {
      display: none;
    }
  }
</style>
